package com.boarsoft.boar.app.biz;

import java.util.List;

import com.boarsoft.boar.entity.AppInst;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.app.AppZoneSlotBiz;
import com.boarsoft.boar.entity.AppZoneSlot;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component
public class AppZoneSlotBizImpl extends SimpleBizImpl implements AppZoneSlotBiz {

	@Override
	@Transactional
	public void save(List<AppZoneSlot> lt) {
		dao.batchSave(lt, 200);
	}

	@Override
	@Transactional
	public int selectMaxNo(String appId, String cluster, String zone, String env) {
		StringBuilder lqb = new StringBuilder();
		lqb.append("select max(no) from ").append(AppZoneSlot.class.getName());
		lqb.append(" where appId = '").append(appId).append("'")
				.append("and cluster = '").append(cluster).append("'")
				.append("and zone = '").append(zone).append("'")
				.append("and env = '").append(env).append("'");
		Object res=dao.createQuery(lqb.toString()).uniqueResult();
		if(res==null){
			return -1;
		}
		return (int) res;
	}

	@Override
	public long selectCount(String appId, String cluster, String zone, String env) {
		StringBuilder lqb = new StringBuilder();
		lqb.append("select count(1) from ").append(AppZoneSlot.class.getName());
		lqb.append(" where appId = '").append(appId).append("'")
				.append("and cluster = '").append(cluster).append("'")
				.append("and zone = '").append(zone).append("'")
				.append("and env = '").append(env).append("'");
		Object res=dao.createQuery(lqb.toString()).uniqueResult();
		if(res==null){
			return 0;
		}
		return (long) res;
	}

	@Override
	@Transactional
	public void delete(List<AppZoneSlot> appZoneSlots) {
		for(AppZoneSlot appZoneSlot:appZoneSlots) {
			StringBuilder sb = new StringBuilder();
			// 删除与节点的关联
			sb.setLength(0);
			sb.append("delete from ").append(AppZoneSlot.class.getName());
			sb.append(" where appId = '").append(appZoneSlot.getAppId()).append("'")
					.append("and cluster = '").append(appZoneSlot.getCluster()).append("'")
					.append("and zone = '").append(appZoneSlot.getZone()).append("'")
					.append("and env = '").append(appZoneSlot.getEnv()).append("'")
					.append("and appInstId = '").append(appZoneSlot.getAppInstId()).append("'");
			dao.executeUpdate(sb.toString());
		}
	}

	@Override
	@Transactional
	public void deleteApp(String appId) {
			StringBuilder sb = new StringBuilder();
			// 删除与节点的关联
			sb.setLength(0);
			sb.append("delete from ").append(AppZoneSlot.class.getName());
			sb.append(" where appId = '").append(appId).append("'");
			dao.executeUpdate(sb.toString());
	}

}